import QQMapWX from '../../lib/qqmap-wx-jssdk.min.js';
Page({
  data: {
    active: 0,
    inLinks: [
      {
        id: 1,
        title: '学校官网',
        src: 'https://www.sdipct.edu.cn/index.htm'
      },
      {
        id: 2,
        title: '百度百科',
        src: 'https://baike.baidu.com/item/%E5%B1%B1%E4%B8%9C%E7%9F%B3%E6%B2%B9%E5%8C%96%E5%B7%A5%E5%AD%A6%E9%99%A2/55624885'
      },
      {
        id: 3,
        title: '招生信息网',
        src: 'https://zs.sdipct.edu.cn/'
      },
    ],
    outLinks: [
      {
        id: 1,
        title: '四六级',
        src: 'https://cet.neea.edu.cn/'
      },
      {
        id: 2,
        title: '计算机二级',
        src: 'https://ncre.neea.edu.cn/'
      },
      {
        id: 3,
        title: '普通话证书',
        src: 'https://bm.cltt.org/#/'
      },
      {
        id: 4,
        title: '教资',
        src: 'https://ntce.neea.edu.cn/'
      }
    ],
    // 经纬度
    latitude: '',
    longitude: '',
    // 逆地址解析后的详细地址 与 天气 、未来三天天气
    address: '',  
    weather:'',
    forecast: [] , 
    // 问好功能可视化操作 与 现实时间
    visible: true,
    timeContent: '',
    loadingCurrent: false,
    loadingFuture: false,
    // 当前时间
    currentDate: '',
    wordsInfo: [
      { id: 1, title: 'apple', description: 'n. 苹果'},
      { id: 2, title: 'apple', description: 'n. 苹果'},
      { id: 3, title: 'apple', description: 'n. 苹果'},
      { id: 4, title: 'apple', description: 'n. 苹果'},
    ]
  },

  onLoad(options) {
    this.getCurrentDateTime();
    this.qqmapsdk = new QQMapWX({
      key: 'WLMBZ-CKEKQ-L3Q54-BO7SP-2FQE7-FFBPD'
    });
    this.getLocation().then(() => {
      this.getWeather();
      this.getForecast();
    }).catch((error) => {
      console.error('定位失败，无法获取天气', error);
      wx.showToast({ title: '定位失败，无法获取天气', icon: 'none' });
    });
  },
  
  // 获取用户经纬度
  async getLocation() {
    try {
      // 1. 获取定位授权
      const authStatus = await wx.getSetting({ scope: 'scope.userLocation' })
      if (!authStatus.authSetting['scope.userLocation']) {
        await wx.authorize({ scope: 'scope.userLocation' })
      }
      // 2. 获取设备经纬度
      const { latitude, longitude } = await wx.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        highAccuracyExpireTime: 60000, // 高精度结果有效期 
        timeout: 10000
      })
      // 更新基础坐标
      this.setData({ latitude, longitude })
      // 3. 触发逆地址解析
      this.reverseGeocode(latitude, longitude)
    } catch (error) {
      console.error('定位流程失败:', error)
      wx.showToast({ title: '获取位置失败', icon: 'none' })
    }
  },
  // 逆地址解析方法->获取位置
  reverseGeocode(lat, lng) {
    this.qqmapsdk.reverseGeocoder({
      location: { latitude: lat, longitude: lng },
      success: res => {
        const { address } = res.result
        this.setData({
          address: address || '未知地址'
        })
      },
      fail: err => {
        console.error('逆解析失败:', err)
        this.setData({ address: '地址解析失败' })
      }
    })
  },

  // 获取天气方法
  async getWeather() {
    const { latitude, longitude } = this.data; 
    if (!latitude || !longitude || latitude === '' || longitude === '') {
      console.error('经纬度信息未获取到，无法获取天气');
      wx.showToast({ title: '请先获取位置信息', icon: 'none' });
      return;
    }

    function formatNumber(num, decimalPlaces) {
      return num.toFixed(decimalPlaces);
    }
    const apiKey = '9db34a243e4f4c9ba2eed1de0034d710'; 
    let latitude1 = formatNumber(latitude, 2);
    let longitude1 = formatNumber(longitude, 2);
    const url = `https://devapi.qweather.com/v7/weather/now?location=${longitude1},${latitude1}&key=${apiKey}`;
    try {
      wx.showLoading({ title: '加载中' });
      const response = await wx.request({
        url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            const weatherData = res.data;
            console.log('天气数据:', weatherData);
            this.setData({
              weather: weatherData.now, 
            });
          } else {
            console.error('获取天气失败:', res);
            wx.showToast({ title: '获取天气失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('请求天气接口失败:', err);
          wx.showToast({ title: '请求天气接口失败', icon: 'none' });
        },
      });
    } catch (error) {
      console.error('获取天气失败:', error);
      wx.showToast({ title: '获取天气失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },
  
  async getForecast() {
    const { latitude, longitude } = this.data; 
    if (!latitude || !longitude || latitude === '' || longitude === '') {
      console.error('经纬度信息未获取到，无法获取天气');
      wx.showToast({ title: '请先获取位置信息', icon: 'none' });
      return;
    }

    // 截取函数
    function formatNumber(num, decimalPlaces) {
      return num.toFixed(decimalPlaces);
    }
    
    const apiKey = '9db34a243e4f4c9ba2eed1de0034d710'; 
    let latitude1 = formatNumber(latitude, 2); 
    let longitude1 = formatNumber(longitude, 2); 
    
    const url = `https://devapi.qweather.com/v7/weather/3d?location=${longitude1},${latitude1}&key=${apiKey}`;
  
    try {
      wx.showLoading({ title: '加载中' });
      const response = await wx.request({
        url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            const forecastData  = res.data.daily;
            console.log('天气数据:', forecastData );
            this.setData({
              forecast : forecastData, 
            });
          } else {
            console.error('获取天气失败:', res);
            wx.showToast({ title: '获取天气失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('请求天气接口失败:', err);
          wx.showToast({ title: '请求天气接口失败', icon: 'none' });
        },
      });
    } catch (error) {
      console.error('获取天气失败:', error);
      wx.showToast({ title: '获取天气失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },
  onChange(event) {
    wx.showToast({
      title: `${event.detail.title}`,
      icon: 'none',
    });
  },
  
  getCurrentDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1; 
    const day = now.getDate();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const formattedDate = `${year}年${month}月${day}日${hours}时${minutes}分`;
    this.setData({
      currentDate: formattedDate,
    });
  },

  onSwitchChange(event) {
    this.setData({
      loadingCurrent: event.detail
    });
  },
  onSwitchFutureChange(event) {
    this.setData({
      loadingFuture: event.detail
    })
  },

  gotoNavigate(e) {
    const direction = e.currentTarget.dataset.direction;
    wx.navigateTo({
      url: `${direction}`,
    });
  },
  
  copyToClipboard(e) {
    const src = e.currentTarget.dataset.src;
    wx.setClipboardData({
      data: src,
      success: () => {
        wx.showToast({
          title: '已复制到粘贴板',
          icon: 'success',
        });
      },
      fail: (err) => {
        wx.showToast({
          title: '复制失败',
          icon: 'none',
        });
        console.error('复制失败:', err);
      },
    });
  },
  
  onClickShow() {
    this.setData({ showCourse: true });
  },

  onClickHide() {
    this.setData({ showCourse: false });
  },
  noop() {},

  onReady() {},

  onShow() {
    this.getTimePeriod();
    this.setData({
      visible: true
    });
    setTimeout(() => {
      this.setData({
        visible: false
      });
    }, 1000);
  },
  getTimePeriod() {
    const now = new Date();
    const hours = now.getHours();
    let timeContent = '';

    if (hours >= 1 && hours <= 4) {
      timeContent = '夜深了，喝杯水，准备休息吧~';
    } else if (hours >= 5 && hours <= 7) {
      timeContent = '清晨的空气是清新的，愿你的心情也是明朗的。';
    } else if (hours >= 8 && hours <= 10) {
      timeContent = '上午的阳光正好，愿你的心情也如这阳光般明媚。';
    } else if (hours >= 11 && hours <= 12) {
      timeContent = '忙碌的上午过去了，愿你的中午时光轻松愉快。';
    } else if (hours >= 13 && hours <= 16) {
      timeContent = '下午的时光，适合思考和行动，愿你有所成就。';
    } else if (hours >= 17 && hours <= 18) {
      timeContent = '傍晚好！愿你在日落的余晖中，感受到生活的美好。';
    } else if ((hours >= 19 && hours <= 22) || hours === 0) {
      timeContent = '夜晚的星空最美，愿你的心情也如这星空般璀璨。';
    }

    this.setData({
      timeContent: timeContent
    });
  },

  onHide() {

  },
  onUnload() {},

  onPullDownRefresh() {},

  onReachBottom() {},

  onShareAppMessage() {}
})